package com.songtech.login;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.songtech.auth.resource.model.Resources;
import com.songtech.auth.role.service.RoleService;
import com.songtech.auth.user.model.User;
import com.songtech.auth.user.service.UserService;
import com.songtech.base.common.BaseConstant;
import com.songtech.base.common.JsonResult;
import com.songtech.base.exception.BusinessException;
import com.songtech.base.listener.SysSessionContext;
import com.songtech.base.redis.RedisUtil;


@Controller
public class LoginController{

	private Logger logger = Logger.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private RedisUtil redisUtil;
	
	
	/**
	 * 用户登录
	 * @param request
	 * @param username
	 * @param password
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/online",method=RequestMethod.POST)
	public JsonResult login(HttpServletRequest request,
			@RequestParam(value="username", required=true) String username,
			@RequestParam(value = "password", required = true) String password) {
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		Subject subject = SecurityUtils.getSubject();
		JsonResult result = new JsonResult();
		
		try {
			subject.login(token);
		} catch (IncorrectCredentialsException e) {
			throw new BusinessException("登录失败，账号密码错误");
		} catch (LockedAccountException e) {
			throw new BusinessException("登录失败，该用户已被冻结");
		} catch (AuthenticationException e) {
			throw new BusinessException("登录失败，该用户不存在");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 判断是否登录成功
		if (subject.isAuthenticated()) {
			logger.info(" login success and return auth data ");
			Map<String, Object> map = new HashMap<String, Object>();
			// 根据角色查询资源权限
			User user = userService.queryUserByName(username);
			List<Resources> rescList = roleService.getRes(username);
			
			// set去重
			Set<Resources> setResc = new HashSet<Resources>(rescList);
			
			// 用户信息放入session中
			HttpSession session = request.getSession();
			SysSessionContext.addSession(session);
			session.setAttribute(session.getId(), user);
			redisUtil.set(session.getId(), user);
			result.status = BaseConstant.SUCCESS_CODE;
			result.msg = BaseConstant.SUCCESS;
			
			map.put("userData", user);
			map.put("menuData", setResc);
			map.put("token", session.getId());
			result.setData(map);
		}
		return result;
	}
	
	/**
	 * system 登出
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/logout",method=RequestMethod.POST)
	public JsonResult logout(HttpServletRequest request) {
		JsonResult result = new JsonResult();
		try {
			String token = request.getParameter("_token");
			HttpSession session = SysSessionContext.getSession(token);
			if(session != null){
				session.removeAttribute(token);
				redisUtil.remove(token);
				result.setStatus(BaseConstant.SUCCESS_CODE);
				result.setMsg(BaseConstant.SUCCESS);
			}else {
				result.setStatus(BaseConstant.SUCCESS_CODE);
				result.setMsg(BaseConstant.SUCCESS);
			}
		} catch (Exception e) {
			throw new BusinessException("退出系统异常，稍后再试");
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value="/unAuth",method=RequestMethod.POST)
	public JsonResult unAuthorize(){
		JsonResult result = new JsonResult();
		result.setStatus(BaseConstant.UNAUTH_CODE);
		return result;
	}
}
